package com.talkweb.ncfw.web.taglib;

import java.util.Map;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.talkweb.ncfw.component.dict.service.IDictService;

/**
 * <p>文件名称: WriteDataDictTag.java</p>
 * <p>文件描述: 数据字典输出标签</p>
 * <p>版权所有: 版权所有(C)2010</p>
 * <p>公　　司: 拓维信息系统股份有限公司</p>
 * <p>内容摘要: 数据字典输出标签，根据数据字典类型将数据字典项写入输出流中</p>
 * <p>其他说明: 其它内容的说明</p>
 * <p>完成日期: 2010-9-26</p>
 * <p>修改记录1:</p>
 * <pre>
 *    修改日期:
 *    修 改 人:
 *    修改内容:
 * </pre>
 * <p>修改记录2：…</p>
 * @author  Wuqingming
 */
public class WriteDataDictTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1441998910851289772L;
	
	public static final String RESULT_TYPE_ARRAY = "array";
	private String dicttypeId = "";
	private String dictId = "";
	private String type = "";

	@SuppressWarnings({ "finally" })
	public int doStartTag() {
		JspWriter out = null;
		try {
			out = pageContext.getOut();
			ApplicationContext ac = WebApplicationContextUtils
					.getRequiredWebApplicationContext(pageContext.getServletContext());
			IDictService dictService = (IDictService) ac.getBean("dictService");
			Object dataDict = dictService.getDataFromDict();
			if(dataDict == null){
				return SKIP_BODY;
			}
			Map dataDictMap = (Map)dataDict;
			if (type.equals(RESULT_TYPE_ARRAY)) {
				StringBuffer sb = new StringBuffer("[");
				int offset = 0;
				for (Object o : dataDictMap.keySet()) {
					if (o.toString().split("~")[0].equals(dicttypeId)) {
						if (offset == 0) {
							sb.append("['" + o.toString().split("~")[1] + "','" + dataDictMap.get(o).toString() + "']");
						} else {
							sb.append(",['" + o.toString().split("~")[1] + "','" + dataDictMap.get(o).toString() + "']");
						}
						offset++;
					}
				}
				sb.append("] ");
				out.print(sb.toString());
			} else {
				for (Object o : dataDictMap.keySet()) {
					if (o.toString().equals(dicttypeId + "~" + dictId)) {
						out.print(dataDictMap.get(o).toString());
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return SKIP_BODY;
		}

	}

	public String getDictId() {
		return dictId;
	}

	public void setDictId(String dictId) {
		this.dictId = dictId;
	}

	public String getDicttypeId() {
		return dicttypeId;
	}

	public void setDicttypeId(String dicttypeId) {
		this.dicttypeId = dicttypeId;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
